package dao

import (
	"github.com/rs/zerolog/log"
	"h8QuestionnaireServer/database"
	"h8QuestionnaireServer/database/entity"
	"strconv"
	"strings"
	"time"
)

func SelectAllQuestionnaire(code string)(dicts []*entity.DictQuestionnaireSelect,dict_emp *entity.DictEmployee, err error){

	err = database.GetPostgreDB().Find(&dicts).Error
	if err != nil{
		return nil, nil, err
	}
	dict_emp = new(entity.DictEmployee)
	err = database.GetPostgreDB().Where("code = ?",code).Find(&dict_emp).Error
	return
}


func InsertQuestionnaireData(QuestionnaireId,Content string,version string)(result int,id string,err error){

	exist,err := IsExist(QuestionnaireId)
	if exist == 99 {
		log.Info().Msgf("questionnaire_id= ? 的记录已存在！",QuestionnaireId)
		result = exist
		id = ""
		return
	} else if exist == -1{
		log.Info().Msgf("后端出现异常")
		result = exist
		id = ""
		return
	}

	nowTime := time.Now()
	dict := &entity.DictQuestionnaire{
		QuestionnaireId: QuestionnaireId,
		Version: version,
		Content: Content,
		QuestionDate: &nowTime ,
	}
	err = database.GetPostgreDB().Save(dict).Error
	if err != nil {
		log.Info().Msgf("提交失败！异常")
		result = -1
		id = ""
		return
	} else {

		id,err = GetIdByQuestionnaireId(QuestionnaireId)
		result = 1
		return
	}
}
//判断是否存在
func IsExist(question_id string)(exist int,err error)  {

	dicts := new([]*entity.DictQuestionnaire)
	err = database.GetPostgreDB().Where("Questionnaire_Id = ?", question_id).First(&dicts).Error
	if err != nil {
		exist = -1
		return
	} else if len(*dicts) > 0{
		exist = 99
		return
	}
	exist = 0
	return
}

//根据question_id获取id，用于生成2维码
func GetIdByQuestionnaireId(questionId string)(id string,err error){

	dict := new(entity.DictQuestionnaireAll)
	string1 := "00000000"
	err = database.GetPostgreDB().Where("Questionnaire_Id = ?", questionId).First(&dict).Error
	if err != nil {
		id = ""
		return id,err
	}
	id = strconv.Itoa(dict.Id)
	var build strings.Builder
	if len(id)<len(string1){
		string1 = string1[0:len(string1) - len(id) - 1]
		build.WriteString(string1)
		build.WriteString(id)
		id = build.String()
	}else if len(id)==len(string1){
		id = string(dict.Id)
	}else{
		id = ""
	}

	return
}


